import {
  getProductDrawingInfoByPage,
  addProductDrawingInfo,
  updateProductDrawingInfo,
  delProductDrawingInfo,
  exportProductDrawingInfo,
  uploadDrawing,
  downloadProductDrawingInfo,
  stopIsActive,
  onIsActive,
  getDrawingTypeList,
  changeDrawing,
} from '@/services/design/productDrawingInfo';
import { tableSearchPublicConfig } from '@/utils/filterUtils';
import { Ellipsis } from '@/components/Ellipsis';
import { PlusOutlined, UploadOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, message, Modal, Tree, Upload, Select } from 'antd';
import { sortTran, filterTran, filterTranNew } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import { history } from 'umi';
const ProductDrawingInfo: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [optionsstandfile, setoptionsstandfile] = useState([]);
  const [file, setFile] = useState();
  const [fileList, setFileList] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [changeStatusColor, setChangeStatusColor] = useState('status-color-white base-status');
  const [form] = Form.useForm();
  const ref = useRef(null);
  const [scrollY, setScrollY] = useState('');

  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
    },
    {
      title: '图纸编号',
      dataIndex: 'drawingCode',
      width: 180,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    /*     {
      title: '变更状态',
      dataIndex: 'changeStatus',
      align: 'center',
      sorter: true,
      render: (text, record, _, action) => <div className={changeStatusColor}></div>,
    }, */
    {
      title: '图纸名称',
      dataIndex: 'drawingName',
      width: 320,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '文件类别',
      dataIndex: 'category',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      valueType: 'select',
      request: async () => {
        const gettype = await getDrawingTypeList(null);
        const productfiletype: any[] = [];
        gettype.data.map((item: any, index: any) => {
          productfiletype.push({ value: item, label: item });
        });
        return productfiletype;
      },
    },
    {
      title: '产品/柜体编号',
      dataIndex: 'productCode',
      width: 220,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      search: false,
    },
    {
      title: '版本号',
      dataIndex: 'version',
      width: 100,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '启用状态',
      dataIndex: 'isActive',
      width: 100,
      align: 'center',
      sorter: true,
      render: (text, record, _, action) => {
        return <div>{record.isActive == 1 ? '是' : '否'}</div>;
      },
      valueType: 'select',
      request: async () => [
        { label: '是', value: 1 },
        { label: '否', value: 0 },
      ],
    },
    {
      title: '图纸打印标识',
      dataIndex: 'printFlag',
      width: 135,
      align: 'center',
      sorter: true,
      render: (text, record, _, action) => {
        return <div>{record.printFlag == 1 ? '已打印' : '未打印'}</div>;
      },
      search: false,
    },
    // {
    //   title: '归档标识',
    //   dataIndex: 'archiveFlag',
    //   width: 120,
    //   align: 'center',
    //   sorter: true,
    //   render: (text, record, _, action) => {
    //     return <div>{record.archiveFlag == 1 ? '已归档' : '未归档'}</div>;
    //   },
    //   search: false,
    // },
    {
      title: '柜体图纸描述',
      dataIndex: 'drawingSpec',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      align: 'center',
      width: 220,
      render: (text, record, _, action) => [
        <a
          key="viewKey"
          onClick={() => {
            if (record.drawingName == null) {
              message.warning('该文件不能预览');
            } else {
              const filetype = record.drawingName.split('.').pop();
              if (filetype == 'pdf' || filetype == 'png' || filetype == 'jpg') {
                const w = window.open('about:blank');
                w.location.href = record.drawingUrl;
              } else {
                message.warning('该文件不能预览');
              }
            }
          }}
        >
          预览
        </a>,
        <a
          key="downloadKey"
          onClick={() => {
            downloadProductDrawingInfo({ id: record.id }).then((res) => {
              const aLink = document.createElement('a');
              document.body.appendChild(aLink);
              aLink.style.display = 'none';
              aLink.href = window.URL.createObjectURL(res);
              aLink.setAttribute('download', `${record.drawingName}`);

              aLink.setAttribute('download', `${record.drawingUrl}`);
              aLink.click();
              document.body.removeChild(aLink);
            });
          }}
        >
          下载
        </a>,
        /*         <a
          key="deleteKey"
          disabled={history.location.state.reviewState == '2'}
          onClick={() => {
            if (history.location.state.reviewState == '2') {
              message.warning('审核后不允许删除图纸');
            } else {
              Modal.confirm({
                title: '删除',
                content: '确定要删除吗',
                okText: '确认',
                cancelText: '取消',
                onOk: async () => {
                  await delProductDrawingInfo({ id: record.id });
                  actionRef.current.reload();
                },
              });
            }
          }}
        >
          删除
        </a>, */
      ],
    },
  ];

  const handleSelect = (record, selected) => {
    if (record.changeStatus === 'status-color-white base-status') {
      // 如果变更状态为白色，则不允许选择
      return;
    }

    if (selected) {
      // 选中行
      setSelectedRowKeys((keys) => [...keys, record.key]);
    } else {
      // 取消选中行
      setSelectedRowKeys((keys) => keys.filter((key) => key !== record.key));
    }
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedRowKeys(selectedRowKeys);
    },
    onSelect: handleSelect, // 调用 handleSelect 函数
  };

  const getproductInfo = async () => {
    // 获取图纸类型
    const gettype = await getDrawingTypeList(null);
    const productfiletype: any[] = [];
    gettype.data.map((item: any, index: any) => {
      if (item == '电气原理图' || item == '箱柜接线表') {
        productfiletype.push({ value: item, label: item + ' *' });
      } else {
        productfiletype.push({ value: item, label: item });
      }
    });
    setoptionsstandfile(productfiletype);
  };
  /**
   * @description:图纸变更上传
   * @return {null}
   */
  const handleSubmit = async () => {
    setConfirmLoading(true);
    form
      .validateFields()
      .then(async () => {
        //获取表单数据
        const productCode = history.location.state.productCode;
        const formData = new window.FormData();
        const formInfo = form.getFieldValue();
        //多文件
        formInfo.file.fileList?.map((item: any) => {
          formData.append('file', item.originFileObj); //需要将file类型的文件转入formData中，不然后端接收不到
        });
        const res = { ...form.getFieldsValue(), productCode: productCode, file: formData };
        // res.drawingId = res.id;
        const result = await uploadDrawing(res);
        console.log(result);
        if (result.code === 0) {
          message.success('成功上传图纸！');
        }
        const { drawingNumber, drawingName, category } = history.location.state;
        console.log(drawingNumber, drawingName, category);
        const isSame =
          drawingNumber === res.drawingNumber &&
          drawingName === res.drawingName &&
          category === res.category;
        console.log(isSame);

        // if (history.location.state.reviewState == 0 || history.location.state.reviewState == 3) {
        //   //待审批、已驳回页面的上传
        //   const result = await uploadDrawing(res);
        //   // 上传图纸成功后的处理部分
        //   if (result != null) {
        //     message.success('上传成功');
        //     form.resetFields();

        //     // 检查图纸编号、图纸名称和文件类别是否与之前的值相同
        //     const { drawingName, drawingNumber, category } = res;
        //     const isSame =
        //       drawingNumber === history.location.state.drawingNumber &&
        //       drawingName === history.location.state.drawingName &&
        //       category === history.location.state.category;

        //     // 根据结果更新变更状态的颜色
        //     if (isSame) {
        //       setChangeStatusColor('status-color-yellow base-status');
        //     } else {
        //       setChangeStatusColor('status-color-green base-status');
        //     }
        //   }
        // } else {
        //   //已审批页面的上传
        //   const result = await changeDrawing(res);
        //   if (result != null) {
        //     message.success('提交审批成功');
        //     form.resetFields();
        //   }
        // }
        form.resetFields();
        setConfirmLoading(false);
        setModalVisit(false);
        actionRef.current!.reload();
      })
      .catch(() => {
        setConfirmLoading(false);
      });
  };

  const handleSubmit2 = async () => {
    setConfirmLoading(true);

    // 1. 验证表单
    form
      .validateFields()
      .then(async () => {
        // 2. 构造请求参数
        const values = form.getFieldsValue();
        const params = { ...values, productCode };

        // 3. 调用提交接口
        const result = await apiSubmit(params);

        if (result) {
          message.success('提交成功');
          actionRef.current!.reload();
        }
      })
      .catch(() => {
        setConfirmLoading(false);
      });
    if (formTitle == '上传图纸') {
      form
        .validateFields()
        .then(async () => {
          const res = { ...form.getFieldsValue(), productCode: history.location.state.productCode };
          const formData = new window.FormData();
          formData.append('file', file);
          res.file = formData;
          res.drawingId = res.id;
          console.log(res);
          console.log(formData.get('file'));
          const result = await uploadDrawing(res);
          if (result != null) {
            message.success('上传成功');
            form.resetFields();
          }
          setConfirmLoading(false);
          setModalVisit(false);
          actionRef.current?.reload();
        })
        .catch(() => {
          setConfirmLoading(false);
        });
    } else if (formTitle == '编辑') {
      form
        .validateFields()
        .then(async () => {
          const res = { ...form.getFieldsValue(), productCode: history.location.state.productCode };
          const formData = new window.FormData();
          formData.append('file', file);
          res.file = formData;
          res.drawingId = res.id;
          console.log(res);
          console.log(formData.get('file'));
          const result = await updateProductDrawingInfo2(res);
          if (result != null) {
            message.success('修改成功');
            form.resetFields();
          }
          setConfirmLoading(false);
          setModalVisit(false);
          actionRef.current.reload();
        })
        .catch(() => {
          setConfirmLoading(false);
        });
      // const res = { ...form.getFieldsValue(), productCode: history.location.state.productCode };
      // const formData = new window.FormData();
      // formData.append('file', file);
      // res.file = formData;
      // res.drawingId = res.id;
      // console.log(res);
      // console.log(formData.get('file'));
      // const result = await updateProductDrawingInfo2(res);
      // if (result != null) {
      //   message.success('修改成功');
      //   form.resetFields();
      // }
    }
  };

  const onFilesChange = (info: any) => {
    setFileList(info.fileList);
  };
  // const onFilesChange = (info: any) => {
  //   // console.log(info.file.status,'info.file.status');
  //   // if (info.file.status === 'uploading') {
  //   //   setLoading(true);
  //   //   return;
  //   // }
  //   // if (info.file.status === 'done') {
  //   //   setLoading(false);
  //   //   setFileList(info.fileList);
  //   //   return;
  //   // }
  //   const isLt = info.size / 1024 / 1024  < 5;
  //   if (isLt) {
  //     setFileList(info.fileList);
  //     console.log('保存file');
  //   }
  // };

  /* 在文件上传之前进行检验 */
  const handleBeforeUpload = (info: any) => {
    //检验文件大小
    // info.size文件大小单位是字节
    const isLt = info.size / 1024 / 1024 < 5;
    if (!isLt) {
      alert(`上传文件大小不能超过 ${5} MB!`);
    }
    // return isLt || Upload.LIST_IGNORE; //这里必须要返回false，来阻止原生的组件的默认action行为，不然会显示存储错误的信息
    return false;
  };

  // const beforeUpload = (file) => {
  //   setFile(file);
  //   return false;
  // };

  return (
    <>
      <ProTable
        headerTitle="技术文件查询"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        search={tableSearchPublicConfig}
        toolBarRender={(action, { selectedRows }) => [
          /*           <div className="projectScheduleGroup" hidden={history.location.state.reviewState == 0}>
            <span>原始：</span>
            <img src="../wks.gif" />
            <span>新增：</span>
            <img src="../zxz.gif" />
            <span>变更：</span>
            <img src="../zt.gif" />
          </div>, */
          <Button
            key="button"
            icon={<ArrowLeftOutlined />}
            onClick={() => {
              history.push({
                pathname: '/design/productDesign',
                query: {
                  tab_state: history.location.state.reviewState, //传参
                },
              });
            }}
            type="primary"
          >
            返回
          </Button>,
          <Button
            key="button"
            hidden={history.location.state.reviewState == 1}
            icon={<UploadOutlined />}
            onClick={() => {
              setCreateOrUpdate(true);
              setFormTitle('上传图纸');
              setModalVisit(true);
              // form.setFieldsValue({
              //   category: optionsstandfile[0].value,
              // });
            }}
            type="primary"
          >
            上传图纸
          </Button>,
          /*           <Button
            hidden={history.location.state.reviewState == 0}
            key="submit"
            type="primary"
            onClick={handleSubmit2}
          >
            提交
          </Button>, */ //todo
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              const filter_ref = { productCode: history.location.state.productCode };
              const filters = filterTranNew(filter_ref);
              exportProductDrawingInfo({
                current: 1,
                pageSize: 150000,
                filters: filters,
              }).then((res) => {
                const aLink = document.createElement('a');
                document.body.appendChild(aLink);
                aLink.style.display = 'none';
                aLink.href = window.URL.createObjectURL(res);

                aLink.setAttribute(
                  'download',
                  `ProductDrawingInfo_${new Date()}_${new Date()}.xlsx`,
                );
                aLink.click();
                document.body.removeChild(aLink);
              });
            }}
            type="primary"
          >
            导出
          </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          const res = { ...params, productCode: history.location.state.productCode };
          const sorters = sortTran(sort);
          const filters = filterTranNew(res);
          const result = await getProductDrawingInfoByPage({
            ...params,
            sorters: sorters,
            filters: filters,
          });
          getproductInfo();
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={
          history.location.state.reviewState == 0
            ? columns.filter(function (item) {
                return item.dataIndex != 'changeStatus';
              })
            : columns
        }
        scroll={{ x: 2000, y: 350 }}
        // scroll={{ x: 2000, y: 400 }}
        rowSelection={{}}
      />
      <Modal
        title={formTitle}
        visible={modalVisit}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => {
          setModalVisit(false);
          form.resetFields();
        }}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          {/* <Form.Item
            label="图纸编号" // 新增图纸编号
            name="drawingNumber" // 表单字段名称为 drawingNumber
            rules={[{ required: true, message: '请输入图纸编号!' }]} // 添加必填规则
          >
            <Input />
          </Form.Item> */}
          <Form.Item
            label="文件类别"
            name="category"
            rules={[{ required: true, message: '请选择文件类别!' }]}
          >
            <Select
              placeholder="请选择文件类别"
              defaultValue=""
              onChange={() => {}}
              options={optionsstandfile}
            />
          </Form.Item>
          <Form.Item
            label="图纸上传"
            name="file"
            rules={[{ required: true, message: '请上传图纸附件!' }]}
          >
            <Upload
              onChange={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
              showUploadList={true}
              beforeUpload={handleBeforeUpload}
              multiple
              maxCount={history.location.state.reviewState == 2 ? 1 : 999}
            >
              <Button icon={<UploadOutlined />}>上传文件</Button>
            </Upload>
          </Form.Item>
          <Form.Item label="图纸描述" name="drawingSpec">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};
export default ProductDrawingInfo;
